import multiprocessing

import requests
import ConnectMySql
import numpy

conn, cursor = ConnectMySql.openConn()


def getMP3AndMV(musicRid):
    # requests.adapters.DEFAULT_RETRIES = 20
    # s = requests.session()
    # s.keep_alive = False
    musicRid = musicRid[0]
    # print(musicRid)
    # 歌曲mp3地址
    mp3Url = "http://antiserver.kuwo.cn/anti.s?type=convert_url&rid=%s&format=aac|mp3&response=url" % musicRid
    # mp3Url = "http://antiserver.kuwo.cn/anti.s"
    mp3Heads = {
        "Accept": "text / html, application / xhtml + xml, application / xml;q = 0.9, image / webp, * / *;q = 0.8",
        "Accept - Encoding": "gzip, deflate, sdch",
        "Accept - Language": "zh - CN, zh;q = 0.8",
        "Cache - Control": "no - cache",
        "Connection": "keep - alive",
        "Cookie": "__guid = 24092650.1673757202672467200.1520663766850.251;anonyid = 1249014470;ad_dist = % 25B1 % 25B1 % 25BE % 25A9;Hm_lvt_cdb524f42f0ce19b169a8071123a4797 = 1522236844, 1522237891, 1522246576, 1522304792;Hm_lpvt_cdb524f42f0ce19b169a8071123a4797 = 1522304831;monitor_count = 1",
        "Host": "antiserver.kuwo.cn",
        "Pragma": "no - cache",
        "Upgrade - Insecure - Requests": "1",
        "User - Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 55.0.2883.87Safari / 537.36"
    }
    mp3Data = {
        "type": "convert_url",
        "rid": musicRid,
        "format": "aac | mp3",
        "response": "url"
    }
    mp3 = requests.get(mp3Url, headers=mp3Heads)
    mp3 = mp3.text
    # 歌曲mv地址
    # mvUrl = "http://www.kuwo.cn/yy/st/mvurl?rid=%s" % musicRid
    # mvUrl = "http://www.kuwo.cn/yy/st/mvurl"
    # mvDate = {
    #     "rid": musicRid
    # }
    # mv = requests.get(mvUrl, mvDate).text
    try:
        # if mv == "res not found":
        #     mv = ""
        cursor.execute("update music set mp3=%s where musicRid=%s", (mp3, musicRid))
        conn.commit()
        print(mp3)
    except Exception as e:
        pass


if __name__ == '__main__':
    pool = multiprocessing.Pool()

    cursor.execute("select musicRid from music")
    # 接收全部的返回结果行
    musicArray = cursor.fetchall()
    musicArray = numpy.array(musicArray)

    for music in musicArray:
        pool.apply_async(getMP3AndMV, args=(music,))

    pool.close()
    pool.join()

    ConnectMySql.closeConn(conn, cursor)
